package com.lagou.handler;

import java.util.concurrent.Callable;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {
  private ChannelHandlerContext context;
  private String param;
  private String result;

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    this.context = ctx;
  }

  /**
   * 收到服务数据，唤醒等待的线程
   *
   * @param ctx
   * @param msg
   * @throws Exception
   */
  @Override
  public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    this.result = msg.toString();
    notify();
  }

  /**
   * 写数据，然后等待唤醒
   *
   * @return
   * @throws Exception
   */
  @Override
  public synchronized Object call() throws Exception {
    context.writeAndFlush(param);
    wait();
    return result;
  }

  public void serParam(String param) {
    this.param = param;
  }
}
